var express = require("express");
var router = express.Router();
const Code = require("./code");
const { Op } = require("sequelize");
const Token = require("./Token");
const crypto = require("crypto");
const Student = require("./model/Student");
const Teacher = require("./model/Teacher");
const RootUser = require("./model/RootUser");
const Courses = require("./model/Courses");
const Scores = require("./model/Scores");

/**************关系************ */
// 老师与课程
Teacher.hasMany(Courses, { targetKey: "id", foreignKey: "teacherId" });
Courses.belongsTo(Teacher);
// 学生与成绩
Student.hasMany(Scores, { targetKey: "id", foreignKey: "studentId" });
Scores.belongsTo(Student);
// 课程与成绩
Courses.hasMany(Scores, { targetKey: "id", foreignKey: "courseId" });
Scores.belongsTo(Courses);
/**************关系************ */
// 获取客户端远程地址
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress
  );
}

router.get("/", async function(req, res) {
  let ip = getClientIp(req);
  console.log(req.headers);
  res.json({
    msg: "欢迎使用just文接口",
    ip
  });
  // Comment.findAll(
  //     {
  //         where: {
  //             articleId: 1
  //         },
  //         // include: [ User,Article]查询带有两个外键全部内容
  //         include: {
  //             model: User,
  //             attributes: ['username']
  //         }
  //     }

  // ).then(resdata => {
  //     res.json(resdata)
  // }).catch(e => {
  //     console.log(e);
  // })
});
//获取注册验证码
router.get("/getcode", function(req, res) {
  let userip =
    req.headers["x-forwarded-for"] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress;
  let code = Math.random()
    .toString(36)
    .substr(2, 4); // 生成4个字符串+数字随机数
  Code.insertkey(code, 5 * 60); //5分钟
  if (Code.findkey(userip)) {
    res.json({
      code: 303,
      message: "操作太频繁"
    });
    return;
  } else {
    Code.insertkey(userip, 5);
    res.json({
      code: 200,
      msg: code,
      message: "5分钟有效"
    });
  }
});

// 校验验证码
router.post("/verifycode", async (req, res) => {
  let { code } = req.body;
  if (!code) {
    res.json({
      code: 404,
      result: "参数不齐全"
    });
    return;
  }
  if (!Code.findkey(code)) {
    res.send({
      code: 303,
      msg: "验证码错误！"
    });
    return;
  }
  res.json({
    code: 200
  });
});

// 管理员登录
router.post("/justwenlogin", async (req, res) => {
  let { code, userId, password } = req.body;
  if (!code || !userId || !password) {
    res.json({
      code: 404,
      result: "参数不齐全"
    });
    return;
  }
  if (!Code.findkey(code)) {
    res.send({
      code: 303,
      msg: "验证码错误！"
    });
    return;
  }
  const finduser = await RootUser.findOne({
    where: {
      userId,
      password
    }
  });
  if (finduser) {
    var token = Token.encrpt({
      userId,
      password
    });
    res.json({
      code: 200,
      token,
      result: finduser
    });
    Code.deletekey(code);
  }
});

// 学生老师登录
router.post("/login", async (req, res) => {
  let { userId, password, tag } = req.body;
  console.log(req.body);
  if (!userId || !password || !tag) {
    res.json({
      code: 404,
      result: "参数不齐全"
    });
    return;
  }
  password = crypto
    .createHash("md5")
    .update(password)
    .digest("hex"); //
  if (parseInt(tag) == 1) {
    const result = await Student.findOne({
      where: {
        sNum: userId,
        password
      }
    });
    if (result) {
      var token = Token.encrpt({
        userId,
        password
      });
      res.json({
        code: 200,
        token,
        result
      });
      return;
    } else {
      res.json({
        code: 404,
        result: "账号或密码错误！"
      });
      return;
    }
  } else {
    const result = await Teacher.findOne({
      where: {
        sNum: userId,
        password
      }
    });
    if (result) {
      var token2 = Token.encrpt({
        userId,
        password
      });
      res.json({
        code: 200,
        token: token2,
        result
      });
      return;
    } else {
      res.json({
        code: 404,
        result: "账号或密码错误！"
      });
      return;
    }
  }
});

//查询所有用户
router.get("/findUser", async (req, res) => {
  if (!Token.decrypt(req.headers.token).token || !req.headers.token) {
    console.log("不允许访问");
    return;
  }
  //分页代码
  var currentPage = parseInt(req.query.currentPage) || 1;
  var limit = parseInt(req.query.pageSize) || 5;
  var offset = (currentPage - 1) * limit;
  //分页代码
  const users = await Student.findAll({
    offset,
    limit,
    order: [["createdAt", "DESC"]]
  });
  res.json({
    code: 200,
    result: {
      data: users
    }
  });
});

//学生指定、年级、学期、获取成绩
router.post("/getonescores", async function(req, res) {
  var { term, grade, sName, exam } = req.body;
  if (!term || !grade || !sName || !exam) {
    res.json({
      code: 404,
      result: "参数不齐全"
    });
    return;
  }
  let data = [];
  if (exam == "全部考试") {
    data = await Scores.findAll({
      where: {
        term,
        grade,
        sName
      },

      attributes: ["grade", "term", "exam", "sName", "subject", "scores", "msg"]
    });
  } else {
    data = await Scores.findAll({
      where: {
        term,
        grade,
        sName,
        exam
      },

      attributes: ["grade", "term", "exam", "sName", "subject", "scores", "msg"]
    });
  }

  if (!data) {
    res.json({
      code: 404,
      result: "参数错误！"
    });
    return;
  }
  var list = datatolist(data);
  res.json({
    code: 200,
    result: list
  });
});

//学生模糊查询获取成绩
router.post("/getlikescores", async function(req, res) {
  var { value, sName } = req.body;
  if (!value || !sName) {
    res.json({
      code: 404,
      result: "参数不齐全"
    });
    return;
  }

  let data = await Scores.findAll({
    where: {
      [Op.and]: [
        {
          [Op.or]: [
            { term: { [Op.like]: "%" + value + "%" } },
            { grade: { [Op.like]: "%" + value + "%" } },
            { exam: { [Op.like]: "%" + value + "%" } }
          ]
        },
        { sName }
      ]
    },
    attributes: ["grade", "term", "exam", "sName", "subject", "scores", "msg"]
  });

  var list = datatolist(data);
  // console.log(list);
  res.json({
    code: 200,
    result: list
  });
});

function datatolist(data) {
  let list = [];
  data.map(mapItem => {
    list.push(mapItem.dataValues);
  });
  console.log(list);
  list.filter(item => {
    if (item.subject == "语文") {
      item.yw = item.scores;
      return true;
    }
    if (item.subject == "数学") {
      item.sx = item.scores;
    }
    if (item.subject == "英语") {
      item.yy = item.scores;
    }
  });

  //根据考试项目分类
  let dataArr = [];
  list.map(mapItem => {
    if (dataArr.length == 0) {
      dataArr.push({
        exam: mapItem.exam,
        term: mapItem.term,
        grade: mapItem.grade,
        List: [mapItem]
      });
    } else {
      let res = dataArr.some(item => {
        //判断相同，有就添加到当前项

        if (
          item.exam == mapItem.exam &&
          item.term == mapItem.term &&
          item.grade == mapItem.grade
        ) {
          console.log("满足");
          item.List.push(mapItem);
          return true;
        }
      });
      if (!res) {
        //如果没找相同日期添加一个新对象
        dataArr.push({
          exam: mapItem.exam,
          term: mapItem.term,
          grade: mapItem.grade,
          List: [mapItem]
        });
      }
    }
  });

  // 合并同类对象
  dataArr.filter(item => {
    item.List.filter((item2, index2) => {
      if (index2 > 0) {
        item2 = Object.assign(item.List[index2], item.List[index2 - 1]);
      }
      item.scores = item.List[item.List.length - 1];
      delete item.scores.scores;
      delete item.scores.subject;
    });
    delete item.List;
    item = item.scores;
  });
  // 最后选料整合
  data = [];
  dataArr.map(item => {
    data.push(item.scores);
  });
  return data;
}
module.exports = router;
